{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "from concurrent.futures import ThreadPoolExecutor, as_completed\n",
    "from concurrent.futures import ProcessPoolExecutor\n",
    "#多进程编程\n",
    "#耗cpu的操作，用多进程编程， 对于io操作来说， 使用多线程编程，进程切换代价要高于线程\n",
    "\n",
    "#1. 对于耗费cpu的操作，多进程优于多线程\n",
    "# def fib(n):\n",
    "#     if n<=2:\n",
    "#         return 1\n",
    "#     return fib(n-1)+fib(n-2)\n",
    "#\n",
    "# if __name__ == \"__main__\":\n",
    "#     with ThreadPoolExecutor(3) as executor:\n",
    "#         all_task = [executor.submit(fib, (num)) for num in range(25,40)]\n",
    "#         start_time = time.time()\n",
    "#         for future in as_completed(all_task):\n",
    "#             data = future.result()\n",
    "#             print(\"exe result: {}\".format(data))\n",
    "#\n",
    "#         print(\"last time is: {}\".format(time.time()-start_time))\n",
    "\n",
    "#2. 对于io操作来说，多线程优于多进程\n",
    "def random_sleep(n):\n",
    "    time.sleep(n)\n",
    "    return n\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    with ProcessPoolExecutor(3) as executor:\n",
    "        all_task = [executor.submit(random_sleep, (num)) for num in [2]*30]\n",
    "        start_time = time.time()\n",
    "        for future in as_completed(all_task):\n",
    "            data = future.result()\n",
    "            print(\"exe result: {}\".format(data))\n",
    "\n",
    "        print(\"last time is: {}\".format(time.time()-start_time))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
